package com.flow.framework.log.helper;

import com.flow.framework.common.util.verify.VerifyUtil;
import com.flow.framework.log.definer.LogPathDefiner;
import com.flow.framework.log.definer.LogFileNameDefiner;
import com.flow.framework.log.definer.LogLevelDefiner;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;

import java.util.HashMap;
import java.util.Map;

/**
 * 日志配置辅助类
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2022/1/15
 */
public class LogConfigHelper {

    private static final String PRODUCT_ENV_SPRING_ACTIVE_PROFILE = "pro";

    private static boolean propertySourceCreated = false;

    public static void config(ApplicationEnvironmentPreparedEvent event) {
        ConfigurableEnvironment environment = event.getEnvironment();
        String loggingConfigPath = environment.resolvePlaceholders("${logging.config:}");
        if (!VerifyUtil.isEmpty(loggingConfigPath)) {
            return;
        }
        String appName = environment.resolvePlaceholders("${spring.application.name}");
        if (VerifyUtil.isEmpty(appName)) {
            appName = "unknown-application-name";
        }
        String activeProfile = environment.resolvePlaceholders("${spring.profiles.active:}");
        String loggingLevel = "DEBUG";

        // 生产环境默认使用INFO
        if (PRODUCT_ENV_SPRING_ACTIVE_PROFILE.equalsIgnoreCase(activeProfile)) {
            loggingLevel = "INFO";
        }

        // 如果服务自定义日志级别，则以自定义为准
        String configLoggingLevel = environment.resolvePlaceholders("${logging.level.root:}");
        if (!VerifyUtil.isEmpty(configLoggingLevel)) {
            loggingLevel = configLoggingLevel;
        }
        String logFilePath = environment.resolvePlaceholders("${logging.file.path:}");
        System.setProperty("logging.level.root", loggingLevel);
        LogLevelDefiner.setSpringLoggingLevel(loggingLevel);
        if (!VerifyUtil.isEmpty(logFilePath)) {
            System.setProperty("logging.file.path", logFilePath);
            LogPathDefiner.setCustomizeLogPath(logFilePath);
        }

        LogFileNameDefiner.setLogFileName(appName);

        if (propertySourceCreated) {
            return;
        }
        Map<String, Object> loggingConfig = new HashMap<String, Object>(1);
        loggingConfig.put("logging.config", "classpath:logback.xml");
        MapPropertySource propertySource = new MapPropertySource("customization_logging_config", loggingConfig);
        environment.getPropertySources().addFirst(propertySource);
        propertySourceCreated = true;
    }
}
